<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import type { FormType } from './index'
import { GetDetailData, PostproductshareData, PutModifyData } from '@/api/modules/productshare'
import detailStore from '@/store/modules/NewCacheData'
import { GetAllData as GetProductOption } from '@/api/modules/merchandiseControl'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

// const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  productId: '',
  shareType: '',
  shareSchema: '',
  sharePic: '',
  shareTxt: '',
  desp: '',
})

const rules = reactive({
  shareTxt: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
})

const shareTypeOptionList = [
  { value: 1, label: '卡片' },
  { value: 2, label: '海报' },
]

const kaType = [
  { value: 11, label: '常规模式' },
  { value: 12, label: '下单模式' },
  { value: 13, label: '大图模式' },
]
const posterType = [
  { value: 21, label: '单张图' },
  { value: 22, label: '合成图' },
  { value: 23, label: '多张图' },
]

interface productListType {
  list: {
    productId: number
    productName: string
    cdnProductPhotoPic: string
    salePrice: number
    flag: number
    guiGeType: number
  }[]
}
const productList = reactive<productListType>({
  list: [],
})

const id = route.query.id as string

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      if (id) {
        // 编辑
        params.id = id
        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'productshareIndex' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        // 添加
        PostproductshareData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('productshareFrom')
            router.push({ name: 'productshareIndex' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`添加失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`添加失败。${errorStr}`)
            }
          }
        })
      }
    }
  })
}

// 图片上传回调
function handleUploadSuccess(url: string) {
  if (url) {
    ruleForm.value.sharePic = url
  }
}

onMounted(async () => {
  if (id) {
    await GetDetailData(id).then(async (res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('productshareFrom')
  }

  const params = qs.stringify({
    FlagList: [7],
  })
  // 获取所有商品
  const ProductOption: any = await GetProductOption(params)
  if (ProductOption.succeeded) {
    productList.list = ProductOption.data
    nextTick(() => {
      productList.list = ProductOption.data
    })
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('productshareFrom', newValue)
    }
  }, { deep: true })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <el-form-item label="转发类型">
              <el-select v-model="ruleForm.shareType" placeholder="请选择转发类型">
                <el-option v-for="item in shareTypeOptionList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </ElCol>
          <ElCol :md="8">
            <el-form-item label="转发模式">
              <el-select v-if="ruleForm.shareType === 1" v-model="ruleForm.shareSchema" placeholder="请选择转发模式">
                <el-option v-for="item in kaType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-select v-if="ruleForm.shareType === 2" v-model="ruleForm.shareSchema" placeholder="请选择转发模式">
                <el-option v-for="item in posterType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </ElCol>
          <ElCol :md="8">
            <el-form-item label="商品">
              <el-select v-model="ruleForm.productId" placeholder="请选择商品">
                <el-option v-for="item in productList.list" :key="item.productId" :label="`${item.productId} - ${item.productName}`" :value="item.productId" filterable />
              </el-select>
            </el-form-item>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="转发标题" :prop="ruleForm.shareType === 1 ? 'shareTxt' : ''">
              <el-input v-model="ruleForm.shareTxt" placeholder="请输入转发标题" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="备注">
              <el-input v-model="ruleForm.desp" placeholder="请输入备注" type="textarea" style="max-width: 500px;" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="转发图">
              <ImageUpload
                :size="1" width="auto" :height="150" :url="ruleForm.sharePic" :ext="['png', 'jpg']"
                @on-success="(imgUrl) => handleUploadSuccess(imgUrl)"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
